package com.hliushi.item.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hliushi.item.pojo.Item;
import com.hliushi.item.pojo.ItemStock;
import com.hliushi.item.service.impl.ItemService;
import com.hliushi.item.service.impl.ItemStockService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author llhuang10
 * @date 2021/9/20 11:18
 */
@Component
public class RedisHandler implements InitializingBean {


    public static final String ITEM_KEY = "item:";
    public static final String ITEM_STOCK_KEY = "item:stock:";

    /**
     * Spring中自带的 jackson
     */
    private static final ObjectMapper MAPPER = new ObjectMapper();
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private ItemService itemService;
    @Resource
    private ItemStockService itemStockService;

    /**
     * 将DB的数据缓存到redis中
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        // 初始化缓存
        // 1.查询商品信息
        List<Item> list = itemService.list();

        // 2.方法缓存
        list.forEach(item -> {
            redisTemplate.opsForValue().set(ITEM_KEY + item.getId(), item);
        });

        // 3.查询商品库存信息
        List<ItemStock> stockList = itemStockService.list();
        stockList.forEach(itemStock -> {
            redisTemplate.opsForValue().set(ITEM_STOCK_KEY + itemStock.getId(), itemStock);
        });
    }
}
